#include "mpu6050.h"
#include "ui_mpu6050.h"
#include <QDebug>
#include "mainwindow.h"
#include <QFile>
#include <fcntl.h> // For open()
#include <unistd.h> // For read() and close()

Mpu6050::Mpu6050(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Mpu6050)
{
    ui->setupUi(this);
    this->setFixedSize(800, 480);

}

Mpu6050::~Mpu6050()
{
    delete ui;
}

void Mpu6050::on_back_pushButton_clicked()
{
    MainWindow *w = new MainWindow();
    w->show();
    this->close();
}

void Mpu6050::on_readdata_pushButton_clicked()
{
    readSensorData();
}

void Mpu6050::readSensorData()
{
    // 打开设备文件
    int fd = open("/dev/I2C1_mpu6050", O_RDONLY);
    if (fd < 0) {
        qDebug() << "Failed to open device file: /dev/I2C1_mpu6050";
        return;
    }

    // 读取六轴数据
    short receive_data[6]; // AX, AY, AZ, GX, GY, GZ
    ssize_t bytesRead = ::read(fd, receive_data, sizeof(receive_data));
    if (bytesRead < 0) {
        qDebug() << "Failed to read from device file.";
        ::close(fd);
        return;
    }

    ::close(fd);  // 关闭文件描述符

    // 显示数据到 QTextEdit
    QString sensorData;
    QTextStream(&sensorData) << "AX=" << receive_data[0] << ", "
                             << "AY=" << receive_data[1] << ", "
                             << "AZ=" << receive_data[2] << "    "
                             << "GX=" << receive_data[3] << ", "
                             << "GY=" << receive_data[4] << ", "
                             << "GZ=" << receive_data[5];
    ui->mpu6050_data_text->setPlainText(sensorData);
}
